﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TimScripts.BF4Rcon
{
    public class PlayerInfoBlockPlayerCollection : IPlayerCollection
    {
        private List<Player> Players;

        public PlayerInfoBlockPlayerCollection(IList<string> data, int offset)
        {
            Players = ParsePlayerInfoBlock(data, offset).ToList();
        }
        public PlayerInfoBlockPlayerCollection(IList<string> data)
            : this(data, 0)
        {

        }

        public Player this[int index]
        {
            get
            {
                if (index >= Count)
                    throw new ArgumentOutOfRangeException("index");

                return Players[index];
            }
        }

        public int Count
        {
            get { return Players.Count; }
        }

        public IEnumerator<Player> GetEnumerator()
        {
            return Players.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return Players.GetEnumerator();
        }

        private static IEnumerable<Player> ParsePlayerInfoBlock(IList<string> data, int offset)
        {
            int index;
            int numPlayers;
            List<string> propertyNames;
            Player newPlayer;

            propertyNames = GetProperties(data, offset);

            index = offset + propertyNames.Count + 1;

            numPlayers = data[index++].ToInt();

            for (int i = 0; i < numPlayers; i++)
            {
                newPlayer = GetPlayerByWordIndex(data, propertyNames, index);
                index += propertyNames.Count;
                yield return newPlayer;
            }
        }

        private static Player GetPlayerByWordIndex(IList<string> data, List<string> propertyNames, int index)
        {
            int numProperties = propertyNames.Count;
            Player newPlayer;
            Dictionary<string, string> playerProperties = new Dictionary<string, string>(numProperties);

            for (int i = 0; i < numProperties; i++)
            {
                playerProperties.Add(
                    propertyNames[i],
                    data[index++]);
            }

            newPlayer = new RconPlayer(playerProperties);

            return newPlayer;
        }

        private static List<string> GetProperties(IList<string> data, int offset)
        {
            int numProperties;
            List<string> propertyNames;
            int index = offset;

            numProperties = data[index++].ToInt();

            propertyNames = new List<string>(numProperties);

            for (int i = 0; i < numProperties; i++)
            {
                propertyNames.Add(data[index++]);
            }

            return propertyNames;
        }
    }
}
